/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lvyh.lightframe.core.consumer.proxy;


import com.lvyh.lightframe.common.util.CommonIdUtil;
import com.lvyh.lightframe.common.util.TraceIdUtil;
import com.lvyh.lightframe.core.cache.RpcReferenceCache;
import com.lvyh.lightframe.core.config.ConsumerConfig;
import com.lvyh.lightframe.core.config.ReferenceConfig;
import com.lvyh.lightframe.core.consumer.reference.ReferenceModel;
import com.lvyh.lightframe.core.filter.ConsumerFilterChain;
import com.lvyh.lightframe.core.filter.FilterChain;
import com.lvyh.lightframe.core.invoke.request.RpcRequest;
import com.lvyh.lightframe.core.invoke.response.RpcResponse;
import com.lvyh.lightframe.core.util.SpringContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author lvyh 2021/05/09.
 */
@Slf4j
public class RpcInvokeHandler {
    private Logger logger = LoggerFactory.getLogger(RpcInvokeHandler.class);
    private Class<?> clazz;
    private ReferenceConfig referenceConfig;

    public RpcInvokeHandler(Class<?> clazz, ReferenceConfig referenceConfig) {
        this.clazz = clazz;
        this.referenceConfig = referenceConfig;
    }

    public Object doInvoke(Object proxy, Method method, Object[] args) throws Exception {
        String className = method.getDeclaringClass().getName();
        ReferenceModel referenceModel = RpcReferenceCache.get(className);
        String version = referenceModel != null ? referenceModel.getVersion() : null;
        String methodName = method.getName();
        Class<?>[] parameterTypes = method.getParameterTypes();
        Object[] parameters = args;
        String[] parameterTypesValue = null;
        boolean generic = false;

        if (Objects.equals(className, Object.class.getName())) {
            logger.info("proxy class method Object.toString() not support!");
            return null;
        }

        ConsumerConfig consumerConfig = SpringContextUtils.getBean(ConsumerConfig.class);
        RpcRequest request = new RpcRequest.Builder()
                .setCreateMillisTime(System.currentTimeMillis())
                .setClassName(className)
                .setMethodName(methodName)
                .setParameterTypes(parameterTypes)
                .setParameters(parameters)
                .setRequestId(CommonIdUtil.generateSimpleUUID())
                .setParameterTypesValue(parameterTypesValue)
                .setGeneric(generic)
                .setReferenceConfig(referenceConfig)
                .setTransport(referenceModel != null ? referenceModel.getTransport() : consumerConfig.getTransport())
                .setTimeout(referenceModel != null ? referenceModel.getTimeout() : consumerConfig.getTimeout())
                .setInvokeType(referenceModel != null ? referenceModel.getInvokeType() : consumerConfig.getInvokeType())
                .setVersion(referenceModel != null ? referenceModel.getVersion() : consumerConfig.getVersion())
                .setLoadBalance(referenceModel != null ? referenceModel.getLoadBalance() : consumerConfig.getLoadBalance())
                .build();

        Map<String, Object> attachment = new HashMap<>();
        attachment.put("traceId", TraceIdUtil.getTraceId());
        request.setAttachment(attachment);

        FilterChain filterChain = SpringContextUtils.getBean(ConsumerFilterChain.class);
        RpcResponse rpcResponse = filterChain.filter(request);
        return rpcResponse.getResult();
    }

}
